// pinia 插件
import type { PiniaPluginContext } from 'pinia'
import { toRaw } from 'vue'

const setStorage = (key: string, value: any) => {
  localStorage.setItem(key, JSON.stringify(value))
}

const getStorage = (key: string) => {
  const item = localStorage.getItem(key)
  try {
    if (item) return JSON.parse(item)
  } catch (e) { /* empty */ }
  return {}
}

type Options = {
  key?: string
}
const __piniaKey__: string = 'application'
export const localStorePiniaPlugin = (option: Options) => {
  return (context: PiniaPluginContext) => {
    const {store} = context
    store.$subscribe(() => {
      setStorage(`${option?.key ?? __piniaKey__}-${store.$id}`,
        toRaw({...store.$state}))
    })

    const initData = getStorage(`${option?.key ?? __piniaKey__}-${store.$id}`)
    return {
      ...initData
    }
  }
}
